/* 
 *  Copyright 2012 CodeMagi, Inc.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.codemagi.servlets.validation;

import com.codemagi.servlets.AppException;
import java.io.InputStream;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.owasp.validator.html.*;

/**
 * Parses HTML input String and validates it against a policy of allowed elements.
 * 
 * NOTE: This validator will throw an AppException if any errors are detected in the scan. 
 * 
 * To scan and filter HTML without throwing exceptions, see AntiSamySilentValidator
 * @see AntiSamySilentValidator
 */
public class AntiSamyValidator implements IValidator {

    Logger log = Logger.getLogger(this.getClass());

    private Policy policy;

    public AntiSamyValidator(InputStream policyFile) {

	try {
	    policy = Policy.getInstance(policyFile);
	} catch (PolicyException e) {
	    log.fatal("ERROR: Policy file not loaded.", e);
	}
    }

    public Object validate(Object obj, HttpServletRequest request) throws AppException {
	if (obj instanceof String) {

	    String input = (String)obj;
	    log.debug("INPUT: " + input);

	    try {
		AntiSamy as     = new AntiSamy();
		CleanResults cr = as.scan(input, policy);

		int numErrors   = cr.getNumberOfErrors();
		if (numErrors > 0) {
		    log.debug("Policy Errors Detected!");

		    List errors = cr.getErrorMessages();
		    StringBuffer errorMessage = new StringBuffer(errors.size() * 128);
		    for (Object oError : errors) {
			log.debug("    " + oError);
			errorMessage.append(oError).append("<br/>");
		    }
		    throw new AppException("HTML validation failed due to illegal markup. " + errorMessage);
		}
		
		String output = cr.getCleanHTML();
		log.debug("OUTPUT: " + output);

		return output;

	    } catch (PolicyException pe) {
		log.debug("Validation failed! - Policy", pe);
		throw new AppException("HTML validation failed due to illegal elements.");

	    } catch (ScanException se) {
		log.debug("Validation failed! - Parser", se);
		throw new AppException("Unable to parse HTML input.");

	    }
	}

	return obj;
    }

}
